package com.hgc.ch02;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by 01367627 on 2019/7/8.
 */
public class CyclicBarrierExample {

    private static ConcurrentHashMap<Long,String> threadMap = new ConcurrentHashMap<>();
    private static CyclicBarrier barrier = new CyclicBarrier(5,new CollectionRunnable());
    private static CountDownLatch latch = new CountDownLatch(5);

    private static class MyRunnable implements Runnable{

        private Random r = new Random();
        @Override
        public void run() {
            threadMap.put(Thread.currentThread().getId(),Thread.currentThread().getName());
            try {
                Thread.sleep(r.nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "睡眠结束");
            try {
                barrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "其他操作");
        }
    }

    private static class CollectionRunnable implements Runnable{

        @Override
        public void run() {
            String result = "";
            for(Map.Entry<Long,String> entry : threadMap.entrySet()){
                result += entry.getValue() + ";";
            }
            System.out.println("开始汇总：" + result);
        }
    }

    public static void main(String[] args) {
        for(int i=0;i<5;i++){
            new Thread(new MyRunnable()).start();
            //latch.countDown();
        }
    }
}
